/**
 * kl yy-ds @2021
 */
package com.cxps.server.order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cxps.cloud.enums.OrderStatus;
import com.cxps.cloud.utils.IdUtils;
import com.cxps.cloud.utils.JsonUtil;
import com.cxps.cloud.utils.NumUtil;
import com.cxps.server.order.domain.*;
import com.cxps.server.order.mapper.OrderMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 订单逻辑层
 *
 * @author YouCai.Liu
 * @since 2021/11/6
 * ...
 */
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 订单信息列表查询
     *
     * @param query
     * @return
     */
    public Page list(OrderQuery query) {

        // 分页查询对象
        Page page = new Page(query.getCurrent(), query.getSize());

        // 查询订单信息
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();

        // 设置排序字段
        qw.orderByDesc("update_time");

        // 设置查询条件
        if (StringUtils.isNotBlank(query.getOrderNum())) {
            qw.eq("order_num", query.getOrderNum());
        }
        if (StringUtils.isNotBlank(query.getOrderStatus())) {
            qw.eq("order_status", query.getOrderStatus());
        }
        if (StringUtils.isNotBlank(query.getOrderSource())) {
            qw.eq("order_source", query.getOrderSource());
        }
        if (StringUtils.isNotBlank(query.getPayType())) {
            qw.eq("pay_type", query.getOrderNum());
        }

        // 执行查询并返回
        return orderMapper.selectPage(page, qw);
    }

    /**
     * 根据订单号查询订单详细信息
     *
     * @param orderNum
     * @return
     */
    public OrderInfoVo details(String orderNum) {
        // 查询订单信息
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        qw.eq("order_num", orderNum);
        OrderEntity orderEntity = orderMapper.selectOne(qw);
        if (null == orderEntity) {
            return null;
        }

        // 构建返回对象
        OrderInfoVo infoVo = new OrderInfoVo();
        infoVo.setOrderEntity(orderEntity);

        // 查询订单信息详细清单
        List<OrderDetailsEntity> orderDetailsEntityList =
                orderMapper.selectOrderDetailsByOrderId(orderEntity.getId());
        infoVo.setOrderDetailsEntities(orderDetailsEntityList);

        return infoVo;
    }

    /**
     * 保存提交订单
     *
     * @param form
     */
    @Transactional
    public String submitOrder(OrderDetailsForm form) {
        // 订单的ID
        String orderId = IdUtils.generateId();

        // 验证订单的完整性
        boolean isFull = true;

        // 订单详细信息集合
        List<OrderDetailsEntity> orderDetailsEntityList = new ArrayList<>();

        // 遍历提交的订单详细信息
        List<OrderDetails> orderDetails = form.getOrderDetails();
        for (OrderDetails orderDetail : orderDetails) {
            String productId = orderDetail.getProductId();
            Double productPrice = orderDetail.getProductPrice();
            Integer productNum = orderDetail.getProductNum();
            Double totalPrice = orderDetail.getTotalPrice();

            if (StringUtils.isBlank(productId)) {
                isFull = false;
                break;
            }
            if (null == productNum) {
                isFull = false;
                break;
            }
            if (null == productPrice) {
                isFull = false;
                break;
            }
            if (null == totalPrice) {
                isFull = false;
                break;
            }

            // 订单详细信息对象
            OrderDetailsEntity orderDetailsEntity = new OrderDetailsEntity();
            orderDetailsEntity.setId(IdUtils.generateId());
            orderDetailsEntity.setProductId(productId);
            orderDetailsEntity.setProductPrice(productPrice);
            orderDetailsEntity.setProductNum(productNum);
            orderDetailsEntity.setTotalPrice(totalPrice);
            orderDetailsEntity.setOrderId(orderId);
            orderDetailsEntityList.add(orderDetailsEntity);
        }

        // 订单信息不完整
        if (!isFull) {
            throw new IllegalArgumentException("订单信息不完整");
        }

        // 生成订单并保存
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setId(orderId);
        String orderNum = NumUtil.unique();
        orderEntity.setOrderNum(orderNum);
        orderEntity.setOrderStatus(0);
        orderEntity.setOrderSource(1);
        orderEntity.setOrderPrice(Double.parseDouble(form.getOrderPrice()));
        orderEntity.setRemark(form.getRemark());
        orderEntity.setVipId(form.getVipId());
        orderEntity.preInsert();
        orderMapper.insert(orderEntity);

        // 保存订单的详细清单信息
        orderMapper.saveOrderDetails(orderDetailsEntityList);

        return orderNum;
    }

    /**
     * 根据订单号修改订单的状态
     *
     * @param orderNum
     */
    public void updateOrderStatus(String orderNum, OrderStatus orderStatus) {
        // 修改订单状态
        orderMapper.updateOrderStatus(orderNum, orderNum, orderStatus.getCode());

        // 如果是 已支付状态，使用feign调用仓库服务，进行发货
        if (orderStatus.getCode().equals(OrderStatus.OK_PAY.getCode())) {
            // feign 仓库服务
        }
    }

    /**
     * 处理监听到的消息
     *
     * @param message 消息载体
     */
    public void handlerMsg(MessageExt message) {
        String tags = message.getTags();
        String msg = new String(message.getBody());

        // Java对象转Json字符串
        // Json字符串转Java对象
        // Json字符串转Map
        Map<String, Object> strObjectMap = JsonUtil.jsonToMap(msg);
        String orderNum = strObjectMap.get("orderNum").toString();
        String payType = strObjectMap.get("payType").toString();
        // 消息tag为OK 则支付成功
        if("OK".equals(tags)){
            // 修改订单状态
            orderMapper.updateOrderStatus(orderNum, payType, OrderStatus.OK_PAY.getCode());
        }
    }
}
